import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 希尔排序
 */
public class ShellSort {

    public static void main(String[] args) {
/*        int[] arr = {5, 4, 3, 2, 1};
        shellSort2(arr);
        for (int i : arr) {
            System.out.print(i + " ");
        }*/

        int[] arr = new int[8000000];
        for (int i = 0; i < 8000000; i++) {
            arr[i] = (int) (Math.random() * 8000000); //生成一个[0, 8000000) 数
        }

        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String date1Str = simpleDateFormat.format(date1);
        System.out.println("插入排序前的时间是=" + date1Str);

        //测试插入排序
        //shellSort(arr);
        shellSort2(arr);

        Date date2 = new Date();
        String date2Str = simpleDateFormat.format(date2);
        System.out.println("插入排序后的时间是=" + date2Str);
    }

    public static void shellSort(int[] arr) {
        int temp = 0;
        //步长循环
/*        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            //根据步长分组，判断分组中的大小
            for (int i = gap; i < arr.length; i++) {

                for (int j = i - gap; j >= 0; j -= gap) {
                    if (arr[j] > arr[j + gap]) {
                        temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }
                }
            }

        }*/
        int gap = arr.length / 2;
        while (gap > 0) {
            //根据步长分组，判断分组中的大小
            for (int i = gap; i < arr.length; i++) {
                for (int j = i - gap; j >= 0; j -= gap) {
                    if (arr[j] > arr[j + gap]) {
                        temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }else {
                        break;
                    }
                }
            }
/*            for (int k : arr) {
                System.out.print(k + " ");
            }
            System.out.println();*/
            //改变步长
            gap = gap / 2;
        }
    }

    //对交换式的希尔排序进行优化->移位法
    public static void shellSort2(int[] arr) {
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {

            for (int i = gap; i < arr.length; i++) {
                int j = i;
                int temp = arr[j];
                if (arr[j] < arr[j - gap]) {
                    while (j - gap >= 0 && temp < arr[j - gap]){
                        arr[j] = arr[j-gap];
                        j -= gap;
                    }
                    arr[j] = temp;
                }
            }
        }
    }
}
